﻿using System;
using System.Reflection;

namespace Middleware
{
    public static class Invoker
    {
        public static byte[] Invoke(byte[] byteMessage) {
            MessageRequest messageRequest = Marshaller.GetMessage(byteMessage) as MessageRequest;
            MessageReply messageReply = new MessageReply();
            object service = ObjectPooling.Get(messageRequest.ObjectID);
            try {
                MethodInfo method = service.GetType().GetMethod(messageRequest.MethodName);
                messageReply.ReturnValue = method.Invoke(service, messageRequest.Parameters);
            } catch (Exception exception) {
                messageReply.IsError = true;
                if (exception.InnerException != null) {
                    messageReply.ErrorMessage = exception.InnerException.Message;
                } else {
                    messageReply.ErrorMessage = exception.Message;
                }
            }
            return Marshaller.GetBytes(messageReply);
        }
    }
}
